from flask import request, jsonify
from com.linkstec.service.user_service import UserService
from com.linkstec.models.user import User
from datetime import datetime

class UserController:
    def __init__(self):
        self.service = UserService()

    def create_user(self):
        data = request.json
        user = User(
            id=None,
            username=data['username'],
            email=data['email'],
            created_at=datetime.now()
        )
        created_user = self.service.create_user(user)
        return jsonify(created_user.__dict__), 201

    def update_user(self, user_id: int):
        data = request.json
        user = User(
            id=user_id,
            username=data['username'],
            email=data['email'],
            updated_at=datetime.now()
        )
        updated_user = self.service.update_user(user)
        return jsonify(updated_user.__dict__)

    def delete_user(self, user_id: int):
        success = self.service.delete_user(user_id)
        return jsonify({"success": success}), 200 if success else 404

    def get_user(self, user_id: int):
        user = self.service.get_user(user_id)
        return jsonify(user.__dict__) if user else ('Not found', 404)

    def list_users(self):
        users = self.service.list_users()
        return jsonify([u.__dict__ for u in users])